<template>
  <div class="app-container">
    <div class="contentBox">
      <div class="searchBox">
        <el-form :model="queryParams" ref="queryRef" :inline="true" @submit.prevent>
          <el-form-item prop="name" style="margin: 0 6px 0 0;">
            <el-input
                class="inputBox"
                v-model="queryParams.name"
                placeholder="请输入品牌名称"
                clearable
                @keyup.enter="handleQuery()"
            />
          </el-form-item>
          <el-form-item style="margin: 0 6px 0 0;">
            <el-button class="normalFormBg searchBtn" icon="Search" @click="handleQuery()"></el-button>
            <el-button class="normalFormBg searchBtn" icon="Refresh" @click="resetQuery"></el-button>
          </el-form-item>
        </el-form>
      </div>
      <el-row :gutter="10" style="margin: 16px 0;">
        <el-col :span="1.5">
          <div class="normalBtn pageFlex pageFlexCenter" v-hasPermi="['gasManage:stockManage:goodBrand:add']"
            @click="handleModalShow('新增品牌')">
            <img src="@/assets/images/plus.png" class="normalBtn_icon">
            <div class="normalBtn_text">新增</div>
          </div>
        </el-col>
      </el-row>
      <el-table
        v-loading="loading"
        :data="dataList"
        border>
        <el-table-column prop="id" label="品牌ID" width="100" :show-overflow-tooltip="true" fixed="left"></el-table-column>
        <el-table-column prop="name" label="品牌名称" width="200" :show-overflow-tooltip="true" />
        <el-table-column prop="cover" label="品牌图标" width="80" align="center">
          <template #default="scope">
            <div class="tableImgBox1">
              <el-image class="img" fit="contain" lazy :src="setCoverUrl(scope.row.cover)"
                 @click="handlePreviewShow(setCoverUrl(scope.row.cover))" v-if="scope.row.cover" />
              <div class="emptyBox" v-else>暂无图标</div>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="isEnable" label="状态" width="150">
          <template #default="scope">
            <div v-for="(item, index) in system_open_status" :key="index" v-show="item.value == scope.row.isEnable">
              <el-tag :type="item.elTagType" v-if="item.elTagType">{{ item.label }}</el-tag>
              <div v-else>{{ item.label }}</div>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="remarks" label="备注说明" :show-overflow-tooltip="true"></el-table-column>
        <el-table-column label="操作" width="340" align="center" fixed="right">
          <template #default="scope">
            <div class="pageFlex pageFlexCenter" style="width: 100%;">
              <div class="pageFlex pageFlexCenter btnSetBox" v-hasPermi="['gasManage:stockManage:goodBrand:list']"
                   @click="handleInfo(scope.row.id)">
                <img src="@/assets/images/fileManage.png" class="img">
                <div class="text">详情</div>
              </div>
              <div class="pageFlex pageFlexCenter btnSetBox" v-hasPermi="['gasManage:stockManage:goodBrand:edit']"
                   @click="handleEdit(scope.row.id)">
                <img src="@/assets/images/edit.png" class="img">
                <div class="text">修改</div>
              </div>
              <div class="pageFlex pageFlexCenter btnSetBox" v-hasPermi="['gasManage:stockManage:goodBrand:delete']"
                   @click="handleDelete(scope.row)">
                <img src="@/assets/images/delete.png" class="img">
                <div class="text">删除</div>
              </div>
            </div>
          </template>
        </el-table-column>
        <template #empty>
          <el-empty description="暂无数据"/>
        </template>
      </el-table>
      <div class="pageFlex pageAlignCenter pageSpaceBetween" style="margin-top: 20px;">
        <div class="totalText">共计 {{total}} 条</div>
        <el-pagination background layout="prev, pager, next" :total="total" :current-page="queryParams.pageNum" :page-size="queryParams.pageSize"
           @current-change="handleCurrentChange"/>
      </div>
    </div>
    <el-drawer v-model="modalShow" direction="rtl" size="600" :title="modalTitle">
      <div class="modalBox" v-if="modalShow">
        <div class="modalBoxContent">
          <el-form
              ref="formRef"
              class="formContent"
              label-width="80"
              :model="form"
              :rules="rules"
              :disabled="modalTitle === '品牌详情'"
          >
            <div class="formContentTop pageFlex pageAlignCenter">
              <div class="line"></div>
              <div class="title">品牌信息</div>
            </div>
            <div class="formContentCenter bgFF">
              <el-form-item label="品牌图标" prop="cover">
                <div class="imgBox">
                  <ImageUpload ref="cover" v-model="form.cover" bg="#FFFFFF" v-if="modalShow"></ImageUpload>
                </div>
              </el-form-item>
              <el-form-item label="品牌名称" prop="name">
                <el-input
                    class="inputBox"
                    v-model="form.name"
                    placeholder="请输入品牌名称"
                    clearable
                />
              </el-form-item>
              <el-form-item prop="sort">
                <template #label>
                  <div class="pageFlex pageAlignCenter">
                    <el-text>排序</el-text>
                    <el-tooltip
                      class="box-item"
                      effect="dark"
                      content="按照倒序排列"
                      placement="bottom"
                    >
                      <el-icon style="color: var(--el-color-primary);cursor: pointer;"><QuestionFilled /></el-icon>
                    </el-tooltip>
                  </div>
                </template>
                <el-input
                  class="inputBox"
                  type="number"
                  v-model="form.sort"
                  placeholder="请输入排序"
                  clearable
                />
              </el-form-item>
              <el-form-item label="备注说明" prop="remarks">
                <el-input
                    class="textareaBox"
                    v-model="form.remarks"
                    type="textarea"
                    placeholder="请输入备注说明"
                    :rows="6"
                />
              </el-form-item>
              <el-form-item label="状态" prop="isEnable">
                <el-radio-group v-model="form.isEnable">
                  <el-radio
                      v-for="dict in system_open_status"
                      :key="dict.value"
                      :value="dict.value"
                  >{{ dict.label }}</el-radio>
                </el-radio-group>
              </el-form-item>
            </div>
          </el-form>
        </div>
        <div class="lineBox" v-if="modalTitle !== '品牌详情'"></div>
        <div class="bottomBox pageFlex pageFlexCenter" v-if="modalTitle !== '品牌详情'">
          <el-button type="primary" :loading="submitLoading" @click="submitNow">确认提交</el-button>
        </div>
        <el-button type="primary" :loading="formLoading" class="modalLoadingBox" v-if="formLoading">加载数据中</el-button>
      </div>
    </el-drawer>
    <el-image-viewer :url-list="srcList" @close="handlePreviewClose" v-if="showPreview"/>
  </div>
</template>
<script setup>
import { onMounted, computed } from 'vue';
import {ElLoading, ElMessageBox} from 'element-plus';
import { searchBrandsApi, addBrandApi, searchBrandByIdApi, editBrandApi, deleteBrandApi } from '@/api/gasManage/stockManage/goodBrand';
import ImageUpload from '@/views/gasManage/components/ImageUpload';
const { proxy } = getCurrentInstance();
const { system_open_status } = proxy.useDict("system_open_status");
const baseUrl = import.meta.env.VITE_APP_BASE_API;
// ---------------------------- 查询 ------------------------------------
const queryParams = ref({
  pageNum: 1,
  pageSize: 10,
  name: ''
})
const loading = ref(false);
const total = ref(0);
const dataList = ref([]);
const showPreview = ref(false);
const srcList = ref([])
const setCoverUrl = computed(()=>{
  return url => {
    if(url){
      return baseUrl+url
    }
    return  ''
  }
})
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}
function resetQuery(){
  proxy.resetForm("queryRef");
  handleQuery();
}
function handleCurrentChange(e){
  queryParams.value.pageNum = e;
  getList();
}
async function getList(){
  loading.value = true;
  let data = await goodsBrandApi(queryParams.value);
  if(data && Array.isArray(data)){
    dataList.value = data;
  }else{
    dataList.value = [];
  }
  loading.value = false;
}
function goodsBrandApi(params){
  return new Promise(resolve => {
    searchBrandsApi(params).then(res => {
      total.value = Number(res.total);
      resolve(Array.isArray(res.rows) ? res.rows : []);
    }).catch(() => {resolve(false)})
  })
}
function handlePreviewShow(link){
  srcList.value = [link];
  showPreview.value = true;
}
function handlePreviewClose(){
  showPreview.value = false;
  srcList.value = [];
}
// ----------------------------弹窗-------------------------------
const modalShow = ref(false);
const modalTitle = ref('');
const formLoading = ref(false);
const submitLoading = ref(false);
const form = ref({
  cover: '',
  name: '',
  sort: '',
  remarks: '',
  isEnable: '1'
})
const rules = ref({
  cover: [{ required: true, message: "品牌图标未上传", trigger: "blur" }],
  name: [{ required: true, message: "品牌名称不能为空", trigger: "blur" }],
  sort: [{ required: true, message: "排序不能为空", trigger: "blur" }],
});
function handleModalShow(name){
  proxy.resetForm('formRef');
  modalTitle.value = name;
  modalShow.value = true;
}
function handleModalHide(){
  modalShow.value = false;
}
async function setFormData(id){
  formLoading.value = true;
  let data = await getBrandDataApi(id);
  if(data){
    data.isEnable = String(data.isEnable);
    form.value = data;
  }
  formLoading.value = false;
}
function getBrandDataApi(id){
  return new Promise(resolve => {
    searchBrandByIdApi(id).then(res => {
      resolve(res.data);
    }).catch(()=>{
      resolve(false);
    })
  })
}
function submitNow(){
  if(submitLoading.value) return;
  proxy.$refs["formRef"].validate(valid => {
    if(valid){
      submitLoading.value = true;
      if(modalTitle.value === '新增品牌'){
        addNow();
      }else{
        editNow();
      }
    }else{
      proxy.$modal.alertWarning('有必填选项未填写，请查看！');
    }
  })
}
// ----------------------------详情-------------------------------
function handleInfo(id){
  handleModalShow('品牌详情');
  setFormData(id);
}
// ----------------------------修改-------------------------------
function handleEdit(id){
  handleModalShow('修改品牌信息');
  setFormData(id);
}
function editNow(){
  delete form.value.createBy;
  editBrandApi(form.value).then(() => {
    submitLoading.value = false;
    handleModalHide();
    proxy.$modal.msgSuccess('修改品牌信息成功');
    getList();
  }).catch(()=>{
    submitLoading.value = false;
  })
}
// ----------------------------新增-------------------------------
function addNow(){
  addBrandApi(form.value).then(() => {
    submitLoading.value = false;
    handleModalHide();
    proxy.$modal.msgSuccess('新增品牌成功');
    getList();
  }).catch(()=>{
    submitLoading.value = false;
  })
}
//----------------------删除--------------------------
function handleDelete(row){
  ElMessageBox.confirm(`确认删除品牌名称为【${row.name}】的数据`,'提示', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(() => {
    deleteNow(row);
  }).catch(() => {})
}
async function deleteNow(row){
  const loading = ElLoading.service({
    lock: true,
    text: '删除中~',
    background: 'rgba(0, 0, 0, 0.7)',
  })
  deleteBrandApi(row.id).then(()=>{
    loading.close();
    proxy.$modal.msgSuccess(row.name+'品牌删除成功');
    getList();
  }).catch(()=>{
    loading.close();
  })
}
onMounted(()=>{
  handleQuery();
})
</script>
<style lang='scss' scoped>
@import "@/assets/styles/public.scss";
:deep(.el-input){
  .el-input__wrapper{
    background-color: $formBgSet;
    box-shadow: none;
  }
}
.normalBtn{
  &_icon2{
    margin-right: 10px;
    color: $normalBtnColor;
  }
}
.loadingBox{
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, .7);
  border: 1px solid transparent;
  box-shadow: none;
  border-radius: 0px;
  position: absolute;
  top: 0;
  left: 0;
}
.app-container{
  width: 100%;
  min-height: calc(100vh - 66px);
  background: #F8F8F9;
}
.tableImg{
  width: 80px;
  height: 80px;
  background-color: $formBgSet;
}
.contentBox{
  width: 100%;
  min-height: $pageMinHeight;
  background-color: #FFFFFF;
  border-radius: 5px;
  box-sizing: border-box;
  padding: 12px;
  .searchBtn{
    width: 32px;
    height: 32px;
    font-size: 12px;
    padding: 0;
    border: none;
    margin: 0 6px 0 0px;
  }
  .btnSetBox{
    padding: 0 10px;
    box-sizing: border-box;
    border-right: 1px solid $borderColor;
    cursor: pointer;
    .text{
      height: 16px;
      line-height: 16px;
      color: var(--el-color-primary);
    }
    .img{
      width: 16px;
      height: 16px;
      margin-right: 2px;
    }
    &:last-child{
      border-right: none;
    }
  }
  .totalText{
    height: 22px;
    font-weight: 400;
    font-size: 14px;
    color: #1D2129;
    line-height: 22px;
  }
}
:deep(.el-drawer){
  .el-drawer__header{
    margin: 0;
    padding-bottom: 20px;
  }
  .el-drawer__body{
    padding: 0;
  }
}
</style>